<template>
  <div class="drawer-layout">
    <el-drawer :title="detailTitle?detailTitle:'编辑'" :visible.sync="drawer" @closed="closedinvitation" size="85%"
      :wrapperClosable="false">
      <div class="layout" style="position: relative" v-loading="loading">
        <el-tabs v-model="activeName">
          <el-tab-pane label="活动基本配置" name="first">
            <el-form ref="basic" label-position="left" :inline="true" :model="basic" size="small" :rules="basicrules">
              <div class="blockquote-box">基本信息</div>
              <div class="form-box">
                <el-form-item label="活动名称" prop="activity_name" class="form-box-item">
                  <el-input clearable maxlength="20" show-word-limit placeholder="请输入活动名称" v-model="basic.activity_name">
                  </el-input>
                </el-form-item>
                <el-form-item label="活动时间" prop="basicTime" class="form-box-item">
                  <el-date-picker clearable value-format="yyyy-MM-dd" @change="basicTimeChange" v-model="basicTime"
                    type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                  </el-date-picker>
                </el-form-item>
                <br>
                <el-form-item label="活动状态" prop="status" class="form-box-item">
                  <el-select v-model="basic.status==-1?2:basic.status" placeholder="请选择状态">
                    <el-option v-for="item in status" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>

            <div class="blockquote-box">海报</div>
              <div class="form-box">
                <el-row :gutter="10">
                  <el-col :xs="12" :sm="12" :md="14" :lg="14" :xl="14">
                    <el-form-item label="海报" class="form-box-item">
                      <logo-upload :single-file="poster" :show-file-list="false" accept="image/jpeg, image/png"
                        @uploadCallback="posterBack" />
                      <div class="form-tip">
                        仅支持.jpg、.png、.jpeg 格式，海报宽高比例1:3；
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="12" :sm="12" :md="10" :lg="10" :xl="10">
                    <div class="placard-box">
                      <div class="placard-title">海报示例</div>
                      <div>
                        <el-image :src="
                            basic.image
                              ? basic.image
                              : require('@/assets/images/jifen.jpg')
                          " style="
                            width: 300px;
                            height: 100px;
                            border-radius: 6px;
                          " />
                      </div>
                      <div class="placard-tip">
                        1.
                        海报页面会展示活动规则和活动时间信息，为不影响海报的美观度，在设计海报时请注意信息的展示；
                        <br />2.
                        规则信息为系统默认生成，设计海报时无需设计活动规则和活动时间相关信息；
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-form>

            <el-divider></el-divider>
            <div class="button-box">
              <el-button @click="basic_information('basic', 'second')" class="next-button">下一步 <i
                  class="el-icon-caret-right el-icon--right"></i></el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="适用范围" name="second">
            <el-form label-position="left" :inline="true" :model="range" ref="range" size="small" :rules="rangerules">
              <div class="blockquote-box">适用范围</div>
              <div class="form-box">
                <el-form-item label="适用区域" class="form-box-item">
                  <el-cascader placeholder="全部" filterable @change="regionChangeWay" v-model="range.appoint_area_select_json"
                    style="width: 100%" :options="regionList" collapse-tags :props="{
                  expandTrigger: 'hover',
                  multiple: true,
                  value: 'id',
                  label: 'name',
                  children: 'children',
                  checkStrictly: false,
                  emitPath: true,
              }" clearable></el-cascader>
                </el-form-item>
                <el-form-item label="用户分组" class="form-box-item">
                  <el-select @change="selectChangeWay('appoint_group_select')" v-model="range.appoint_group_select"
                    multiple clearable collapse-tags placeholder="全部">
                    <el-option v-for="item in groupingList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="用户等级" class="form-box-item">
                  <el-select @change="selectChangeWay('appoint_level_select')" v-model="range.appoint_level_select"
                    multiple clearable collapse-tags placeholder="全部">
                    <el-option v-for="item in gradeList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="用户标签" class="form-box-item">
                  <el-select clearable @change="selectChangeWay('appoint_tag_select')" style="width: 100%"
                    v-model="range.appoint_tag_select" multiple collapse-tags placeholder="全部">
                    <el-option-group v-for="group in TagCategoryAll" :key="group.category_name"
                      :label="group.category_name">
                      <el-option v-for="item in group.child" :key="item.id" :label="item.tag_name" :value="item.id">
                      </el-option>
                    </el-option-group>
                  </el-select>
                </el-form-item>

              </div>
              <div class="blockquote-box">可参与活动的用户</div>
              <div class="form-box">
                <div class="table-top">
                  <div class="table-top-left">
                    <div>所有用户：{{ rangeCanJoinUsertotal }}</div>
                    <div>黑名单用户：{{ joinblackIds.length }}</div>
                    <div>重复用户：{{ rangeHasJoinUserTotal }}</div>
                  </div>
                  <div class="table-top-right">
                    <div>
                      <el-button style="height: 30px" type="primary" @click="addConfig('黑名单')" plain
                        size="small">配置黑名单</el-button>
                    </div>
                    <div>
                      <el-button style="height: 30px" type="primary" @click="addConfig('重复对象')" plain
                        size="small">配置重复</el-button>
                    </div>
                  </div>
                </div>
                <div>
                  <el-table v-loading="rangeCanJoinUserLoading" highlight-current-row :data="CanJoinUserList"
                    :header-cell-style="{
                        'background-color': '#f3f8fe',
                        color: '#606266',
                        height: '50px',
                    }" style="width: 100%">
                    <el-table-column align="center" prop="id" label="用户id"></el-table-column>
                    <el-table-column align="center" prop="nickname" label="用户昵称"></el-table-column>
                    <el-table-column align="center" prop="region" label="用户区域">
                      <template slot-scope="scope">
                        {{
                                scope.row.province_name
                                    ? scope.row.province_name
                                    : "-"
                            }}
                        {{ scope.row.city_name ? scope.row.city_name : "-" }}
                      </template>
                    </el-table-column>
                    <el-table-column width="200" align="center" prop="group" label="用户群组">
                      <template slot-scope="scope">
                        <!-- 用户群组：提示多个群组需要用分隔符区分，‘空格’+‘/’,超过三个显示超过的数量 -->
                        <el-tooltip class="item" effect="dark" :content="scope.row.group_name" placement="top">
                          <div v-if="scope.row.group_name" style="display: flex; justify-content: center">
                            <div>{{ scope.row.group_name }}</div>
                          </div>
                        </el-tooltip>
                        <div v-if="!scope.row.group_name">-</div>
                      </template>
                    </el-table-column>
                    <el-table-column width="200" align="center" prop="tag" label="用户标签">
                      <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" :content="scope.row.tag_name.join('/')" placement="top">
                          <div v-if="scope.row.tag_name.length !== 0" style="display: flex; justify-content: center">
                            <div v-if="index < 3" v-for="(item, index) in scope.row.tag_name" :key="index">
                              {{ item }} /
                            </div>
                            <div v-if="scope.row.tag_name.length > 3" class="table-num">
                              + {{ scope.row.tag_name.length }}
                            </div>
                          </div>
                        </el-tooltip>
                        <div v-if="scope.row.tag_name.length == 0">-</div>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" prop="status" label="参与状态"></el-table-column>
                    <el-table-column fixed="right" width="100" prop="address" label="操作" align="center">
                      <template slot-scope="scope">
                        <el-button type="text" @click="joinblack([scope.row])">
                          加入黑名单
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <pagination v-show="rangeCanJoinUsertotal > 0" :total="rangeCanJoinUsertotal"
                    :page.sync="rangeCanJoinUserSearch.page" :limit.sync="rangeCanJoinUserSearch.count"
                    @pagination="getRangeCanJoinUserListWay" />
                </div>
              </div>
            </el-form>
            <el-divider></el-divider>
            <div class="button-box">
              <el-button @click="activeName = 'first'" icon="el-icon-caret-left" class="next-button">上一步</el-button>
              <el-button @click="basic_information('range', 'third')" class="next-button">下一步 <i
                  class="el-icon-caret-right el-icon--right"></i></el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="活动规则" name="third">
            <el-alert
                style="margin:20px 0 20px 0"
                title="奖励说明:"
                type="warning"
                :closable="false"
              >
                送积分活动本页面只需要配置活动商品即可，其余参数在商品增值插件中设置；
              </el-alert>
              <div class="blockquote-box" style="margin-bottom: 26px;">消费奖励</div>
              <el-form label-position="left" :inline="true" :model="configuration" ref="configuration" size="small" :rules="configurationrules">
                <el-form-item required label="配置活动商品" class="form-box-item" style="margin-left: 10px;">
                    <el-button
                      type="primary"
                      style="height: 30px"
                      @click="addwardConfig('配置指定商品')"
                      >配置指定商品<span >({{ reward_task_goods_ids.length }})</span
                      ></el-button >
              </el-form-item>
              <!--  -->
              <div style="margin-left: 12px;">
                <el-form-item required label="订单金额区间设置">
                </el-form-item>
                <div v-for="(item,index) in configuration.rule_range" style="display: flex;justify-content: flex-start;margin: 0 0 10px 131px;" :key="index">
                    <el-form-item :prop="'rule_range.' + index + '.section_start'">
                      <el-input @input="ection_startWay(item)" controls-position="right" v-model.trim="item.section_start" maxlength="6" placeholder="起始金额" style="width: 150px;">
                      </el-input>
                      <span class="tips" v-if="item.section_startBool">整数,不能大于截止金额</span>
                    </el-form-item>
                    <span style="margin: 5px 10px 10px 0px;">--</span>
                    <el-form-item :prop="'rule_range.' + index + '.section_end'">
                      <el-input @input="section_endWay(item)" controls-position="right" v-model.trim="item.section_end" maxlength="6" placeholder="截止金额" style="width: 150px;">
                      </el-input>
                     <span class="tips" v-if="item.section_endBool">整数,不能小于起始金额</span>
                    </el-form-item>
                    <el-button type="warning" style="height: 30px"
                      @click="addproducts(index)">配置加购商品<span>({{ item.goods_ids.length }})</span></el-button>
                      <div style="margin-left: 30px;">
                        <el-button @click="addRuleWay" type="primary" icon="el-icon-plus" circle></el-button>
                        <el-button @click="delRuleWay(item)" v-if="configuration.rule_range.length > 1" type="danger" icon="el-icon-minus" circle></el-button>
                        </div>
                        <span style="color: #606266;font-size: 14px;line-height: 30px;margin-left: 6px;">（助农活动:配置指定商品+订单金额区间设置+区间对应配置加购商品）</span>
                </div>
              </div>

              <!--  -->
              </el-form>
            <el-divider></el-divider>
            <div class="button-box">
              <el-button @click="activeName = 'second'" icon="el-icon-caret-left" class="next-button">上一步</el-button>
              <el-button @click="basic_information('configuration', 'fourth')" class="next-button">下一步 <i
                  class="el-icon-caret-right el-icon--right"></i></el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="活动说明" name="fourth">
            <el-form label-position="left" :inline="true" size="small">
              <div class="blockquote-box">活动简介&规则说明</div>
              <div class="form-box">
                <el-form-item label="活动简介" required class="form-box-item">
                  <el-input type="textarea" style="width: 500px;" :rows="10" placeholder="请输入内容" v-model="basic.remark">
                  </el-input>
                </el-form-item>
                <el-form-item label="活动规则" required class="form-box-item">
                  <editor-text v-model="basic.explain" :height="240" @input="editorclick" />
                </el-form-item>
              </div>
            </el-form>
            <el-divider></el-divider>
            <div class="button-box">
              <el-button @click="activeName = 'third'" icon="el-icon-caret-left" class="next-button">上一步</el-button>
              <el-button @click="basic_information('range', 'Plugins')" class="next-button">下一步 <i
                  class="el-icon-caret-right el-icon--right"></i></el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="商品增值插件" name="Plugins">
            <Plugins  @updateCheckData="handleUpdateCheckData"  @child-event="toactivename" :shappingid="editId"  :shapdata="reward_task_goods_v2" :editdata="plugin_gaindata"></Plugins>
            <el-divider></el-divider>
            <div class="button-box">
              <el-button @click="activeName = 'fourth'" icon="el-icon-caret-left" class="next-button">上一步</el-button>
              <el-button @click="basic_information('range', 'Distribution')" class="next-button">下一步 <i
                  class="el-icon-caret-right el-icon--right"></i></el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="商品分销插件" name="Distribution">
            <Distribution  ref="childRef" @isitenabled="isitenabled"  @updateCheckDatav2="handleUpdateCheckDatav2"  :openplugin_retail="openplugin_re" :editdata="plugin_retaildata"  :shapdata="reward_task_goods_ids" @child-event="toactivename" :shappingid="editId"></Distribution>
            <el-divider></el-divider>
            <div class="button-box">
              <el-button @click="activeName = 'Plugins'" icon="el-icon-caret-left" class="next-button">上一步</el-button>
              <el-button class="next-button" @click="saveSubmit">保存</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>
    <config ref="config" v-if="ifShowConfig" :userIds="userIds" :regionList="regionList" :groupingList="groupingList"
      :TagCategoryAll="TagCategoryAll" :gradeList="gradeList" :ConfigTitle="ConfigTitle" />
      <!-- 指定商品抽屉 -->
      <productConfig
      v-if="ifShowProductConfig"
      :goodsType="goodsType"
      :goodsIdArr="reward_task_goods_ids"
      :goodsIdsRowList="reward_task_goods_ids_row"
      :productConfigTitle="productConfigTitle"
    ></productConfig>
    <!-- 助农 -->
    <addproduct v-if="addProductConfig" :goodsIdArr="reward_tasks_goods_ids" :productConfigTitle="titles"
         ></addproduct>
  </div>
</template>

<script>
import config from "./config";
import productConfig from "../components/productConfig";
import addproduct from "../components/addproduct";
import Distribution from "../distribution";
import Plugins from "../plugins";
import LogoUpload from "@/components/FileUpload";
  import {
    rangeCanJoinUserList
  } from "@/api/index";
  import {
    SaveSign,
  getBonusDetail,
} from '@/api/activity/agriculturev2'

  export default {
    name: 'drawer',
    props: [
      "detailTitle",
      "regionList",
      "groupingList",
      "TagCategoryAll",
      "gradeList",
    ],
    components: {
      config,
      productConfig,
      Plugins,
      LogoUpload,
      Distribution,
      addproduct
    },
    watch: {
      activeName: {
        handler(oldVal, newVal) {
          if(oldVal === 'second') {
            this.getRangeCanJoinUserListWay();
          }else if(oldVal === 'Plugins') {
            let uniqueGoodsIds = new Set();
            this.configuration.rule_range.forEach(item => {
              item.goods_ids.forEach(goodsId => {
                uniqueGoodsIds.add(goodsId); 
              });
            });
            let arr = Array.from(uniqueGoodsIds);
            this.reward_task_goods_v2 = arr
            if(this.objRes!='') {
              this.plugin_gaindata = this.objRes.plugin_gain;
            }
          }else if(oldVal === 'Distribution'){
            if(this.objRes!='') {
              this.plugin_retaildata = this.objRes.plugin_retail;
              this.plugin_gaindata = this.objRes.plugin_gain;

            }
          }else if(oldVal === 'third'){
           
          }
        },
        deep: true,
      },
    },
    data() {
      return {
        screntindex:0,
        titles:'配置加购商品',
        addProductConfig: false, // 已选商品抽屉
        reward_tasks_goods_ids:[],
        distribution_shuju:{

        },
        distzengzhi_shuju:{

        },
        objRes:'',
        rule_shoping:[],
        goodsType: "全部",
        reward_task_goods_v2:[],//增值插件的商品
        reward_task_goods_ids: [], // 任务商品数组
        reward_task_goods_ids_row: [], // 任务商品数组
        total_num: 0,
        gif_num: 0,
        productConfigTitle: "", // 已选商品库标题
        ifShowProductConfig: false, // 已选商品抽屉
        radio: '1',
        activeName: "first", //默认第一步
        loading: false,
        drawer: true,
        openplugin_re: '',
        plugin_retail:{
          is_open:0,
          goods_list:[],
        },
        ifShowadd: false, // 指定商品抽屉
        goodsIds: [],  //已添加的指定商品id
        goodsIdsRow: [],
        plugin_gaindata:[],
        plugin_retaildata:[],
        plugin_gain:{
          is_open:1,
          goods_list:[],
        },
        status: [{
            name: "关闭",
            id: 2
          },
          {
            name: "开启",
            id: 1
          },
        ],
        poster: {}, // 邀请海报回显
        // 基本信息
        basic: {
          explain: "",
          remark: "",
          image: "", // 活动图片
          activity_name: "", // 签到活动名称
          start_time: "", // 开启时间
          end_time: "", // 结束时间
          status: 2, //状态
        },
         // 适用范围
         range: {
          appoint_area_select_json: [],
          appoint_area_select: [],
          appoint_group_select: [],
          appoint_tag_select: [],
          appoint_level_select: [],
          user_black: [], // 黑名单用户id
        },
          // 活动规则
        configuration: {
          awardIds: [], // 指定商品id
          rule_range:[
            {
              section_start:null,
              section_end:null,
              section_startBool:true,
              section_endBool:true,
              goods_row_ids:[],
              goods_ids:[]
            }
          ],
        },
        // 基本信息时间段
        basicTime: [],
        //基本信息校验
        basicrules: {
          activity_name: [{
            required: true,
            validator: (rule, value, callback) => {
              let req = /[^0-9a-zA-Z\u4e00-\u9fa5]/g;
              if (!value) {
                callback(new Error("请输入活动名称"));
              } else {
                if (req.test(value)) {
                  callback(new Error("活动名称中不能存在特殊字符"));
                } else {
                  callback();
                }
              }
            },
            trigger: "change",
          }, ],
          basicTime: [{
            required: true,
            validator: (rule, value, callback) => {
              if (this.basicTime.length == 0) {
                return callback(new Error("请选择活动的时间段"));
              } else {
                callback();
              }
            },
            trigger: "change",
          }, ],
          status: [{
            required: true,
            validator: (rule, value, callback) => {
              callback();
            },
            trigger: "change",
          }, ],
        },

        // 适用范围规则
        rangerules: {},
        configurationrules: {},
        // 满足条件的可参与用户列表
        CanJoinUserList: [],
        rangeCanJoinUserLoading: false, // 使用范围使用用户列表
        rangeCanJoinUsertotal: 0, // 使用范围使用用户列表总条数
        joinblackIds: [], // 黑名单id列表
        rangeHasJoinUserTotal: 0, // 重复用户数
        ifShowConfig: false, // 控制配置黑名单重复抽屉显示隐藏
        userIds: [], // 向配置黑名单重复抽屉传递的参数
        ConfigTitle: "", // 配置黑名单重复抽屉标题的参数
        // 获取重复参与活动用户列表
        rangeCanJoinUserSearch: {
          remove_activity_id: "", // 需要排除的活动ID（修改活动，需要传当前活动ID）
          appoint_area_select: "", // 选择的地区ID（市ID，多个以,分开）
          appoint_level_select: "", // 选择的用户等级ID（多个以,分开）
          appoint_group_select: "", // 选择的用户分组ID（多个以,分开）
          appoint_tag_select: "", // 选择的用户标签ID（多个以,分开）
          user_black: "", // 黑名单用户ID（多个以,分开）
          page: 1,
          count: 10,
        },
        //签到参数校验
        taskRules: {
          conversion_validity_day: [{
            required: true,
            validator: (rule, value, callback) => {
              let req = /^[0-9]*$/; // 正则表达式：只能是数字
              if (value === "") {
                callback(new Error("请输入签到天数"));
              } else if (!req.test(value)) {
                callback(new Error("只能输入正整数"));
              } else {
                callback();
              }
            },
            trigger: "change",
          }, ],
        },
        // 活动规则
        explainBool: false,
        //活动简介
        editId:'',//编辑ID
      }
    },
    methods: {
      // 回显加购商品的数据
      addwardIdsRowWays(row) {
        this.configuration.rule_range[this.screntindex].goods_row_ids = row
      },
      // 回显加购商品的ID
      addwardIdsWays(row) {

        this.configuration.rule_range[this.screntindex].goods_ids = row
      },
      closeConfigs() {

        this.addProductConfig = false;
      },
      //加购商品
      addproducts(index) {
        this.screntindex = index
        this.reward_tasks_goods_ids = this.configuration.rule_range[index].goods_ids
        this.addProductConfig = true;
      },
      ection_startWay(item) {
        const req = /\D/g;
        item.section_startBool = req.test(item.section_start);
        if (!item.section_startBool && item.section_end) {
          if (Number(item.section_end) < Number(item.section_start)) {
            item.section_startBool = true;
          }
        }
        this.$forceUpdate();
      },
      section_endWay(item) {
        const req = /\D/g;
        item.section_endBool = req.test(item.section_end);
        if (!item.section_endBool && item.section_start) {
          if (Number(item.section_end) < Number(item.section_start)) {
            item.section_endBool = true;
          }
        }
        this.$forceUpdate();
      },
      // 添加更多规则
      addRuleWay() {
        this.configuration.rule_range.push({
          id: this.configuration.rule_range.length + "" + new Date().getTime(),
          section_start:null,
          section_end:null,
          section_startBool:true,
          section_endBool:true,
          goods_row_ids:[],
          goods_ids:[]
        });
      },
      // 删除规则
      delRuleWay(row) {
        var arr = [];
        this.configuration.rule_range.forEach((item) => {
          if (item.id !== row.id) {
            arr.push(item);
          }
        });
        this.configuration.rule_range = arr;
      },
      // add
      editorclick(e) {
        this.basic.explain = e;
      },
      getAwardInfoWay(row) {
        this.loading = true;
        this.editId = row.id;
        getBonusDetail({ id: row.id }).then((res) => {
          this.objRes = res.data;
          this.basic.activity_name = this.objRes.activity_name
          this.basic.explain =this.objRes.explain
          this.basic.remark = this.objRes.remark
          this.basic.status = this.objRes.status
          this.posterBack({
            url: this.objRes.image
          });
        this.basicTime = [this.objRes.start_time,this.objRes.end_time]
        this.basic.start_time = this.objRes.start_time
        this.basic.end_time = this.objRes.end_time
        this.openplugin_re = this.objRes.plugin_retail.is_open
        this.regionChangeWay(this.objRes.appoint_area_select_json);
        this.range.appoint_group_select = this.objRes.appoint_group_select;
        this.range.appoint_level_select =  this.objRes.appoint_level_select;
        this.range.appoint_tag_select = this.objRes.appoint_tag_select;
        this.range.user_black =this.objRes.user_black.toString();
        this.reward_task_goods_ids = this.objRes.goods_ids;

        this.configuration.rule_range = this.objRes.rule_range

        this.submitLoading = false
        this.loading = false;
        })
      },
      handleUpdateCheckData(checkData) {
        // 这里接收到子组件传递过来的 checkData
        this.plugin_gain.goods_list = checkData
      },
      isitenabled(data){
        this.plugin_retail.is_open = data
      },
      handleUpdateCheckDatav2(data){
        this.plugin_retail.goods_list = data
      },
      // 上传邀请海报回调
      posterBack(file) {
        this.poster = file;
        this.basic.image = file.url;
      },
      toactivename(name){
        this.activeName = name;
      },
       //加入黑名单
    joinblack(row) {
      this.$confirm("确定要将用户添加到黑名单吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (row.length !== 0) {
            row.forEach((item) => {
              this.joinblackIds.push(item.id);
            });
          }
          this.rangeCanJoinUserSearch.user_black = this.joinblackIds.toString();
          this.getRangeCanJoinUserListWay();
          this.$message({
            type: "success",
            message: "添加成功!",
          });
          this.userIds = this.joinblackIds;
          this.$refs.config.getList(this.joinblackIds);
        })
        .catch(() => {});
    },
    // 移除黑名单
    removeBlacklist(row) {
      var _this = this;
      _this
        .$confirm("确定要将用户移出黑名单吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          var arr = [];
          if (row.length !== 0) {
            row.forEach((item) => {
              arr.push(item.id);
            });
          } else {
            arr = [];
          }
          _this.joinblackIds = _this.getArrDifference(arr, _this.joinblackIds);
          _this.rangeCanJoinUserSearch.user_black =
            _this.joinblackIds.toString();
          _this.getRangeCanJoinUserListWay();
          _this.$message({
            type: "success",
            message: "移出成功!",
          });
          _this.userIds = _this.joinblackIds;
          _this.$refs.config.getList(_this.joinblackIds);
        })
        .catch(() => {});
    },
      // 关闭添加抽屉
      closedinvitation() {
        this.$parent.closedetail();
      },
      //配置指定商品
      addwardConfig(title) {
        this.ifShowProductConfig = true;
        this.productConfigTitle = title;
    },
     // 选择的指定商品
     addwardIdsRowWay(row) {
      this.reward_task_goods_ids_row = row;
    },
    // 商品
      addwardIdsWay(row) {
        this.reward_task_goods_ids = row;
      },
    closeConfig() {
      this.ifShowadd = false;
    },
        //批量添加指定商品
        addproductWay(row) {
          row.forEach((item) => {
            this.goodsIds.push(item.id);
          });
          this.$message({
            message: "添加成功",
            type: "success",
          });
        },
        addproductRowWay(row) {
          console.log(row);
          this.goodsIdsRow.push(...row);
        },
      // 选择活动日期之后直接赋值
      basicTimeChange(val) {
        if (val.length !== 0) {
          this.basic.start_time = val[0];
          this.basic.end_time = val[1];
        } else {
          this.basic.start_time = "";
          this.basic.end_time = "";
        }
      },
      // 基本信息点击下一步调用
      basic_information(data,activeName) {
        this.activeName = activeName;
      },
      // 获取可参与列表
      getRangeCanJoinUserListWay() {
        this.rangeCanJoinUserLoading = true;
        rangeCanJoinUserList(this.rangeCanJoinUserSearch).then((res) => {
          this.rangeCanJoinUserLoading = false;
          this.loading = false;
          if (res.code !== 200 || res.status !== 1) {
            this.$messages.error(res.msg);
            return;
          }
          this.CanJoinUserList = res.data.list;
          this.rangeCanJoinUsertotal = res.data.total;
        });
      },
      // 选择区域调用
      regionChangeWay(val) {
        var arr = [];
        val.forEach((item) => {
          arr.push(item[1]);
        });
        this.range.appoint_area_select_json = val;
        this.rangeCanJoinUserSearch.appoint_area_select = arr.toString();
        // this.range.appoint_area_select = arr.toString();
        this.getRangeCanJoinUserListWay();
      },
      // 下拉框选择调用
      selectChangeWay(name) {
        if (name == "appoint_group_select") {
          this.rangeCanJoinUserSearch.appoint_group_select =
            this.range[name].toString();
        } else if (name == "appoint_level_select") {
          this.rangeCanJoinUserSearch.appoint_level_select =
            this.range[name].toString();
        } else if (name == "appoint_tag_select") {
          this.rangeCanJoinUserSearch.appoint_tag_select =
            this.range[name].toString();
        }
        this.getRangeCanJoinUserListWay();
      },
      getArrDifference(arr1, arr2) {
      return arr1.concat(arr2).filter(function (v, i, arr) {
        return arr.indexOf(v) === arr.lastIndexOf(v);
      });
    },
      //打开配置黑名单重复抽屉
      addConfig(title) {
        this.ifShowConfig = true;
        this.$nextTick(() => {
          if (title == "黑名单") {
            this.userIds = this.joinblackIds;
          } else if (title == "重复对象") {
            this.userIds = this.joinblackIds;
          }
          this.ConfigTitle = title;
        });
      },
      // 关闭配置黑名单重复抽屉
      closeConfig() {
        this.ifShowConfig = false;
        this.ifShowProductConfig = false;
      },
      // 提交按钮
      saveSubmit() {
        const p1 = new Promise((resolve, reject) => {
          this.$refs.basic.validate((valid, error) => {
            if (valid) {
              resolve();
            } else {
              this.activeName = "first";
              reject({
                error: error,
                name: "first",
              });
              return;
            }
          });
        });
        const p2 = new Promise((resolve, reject) => {
          this.$refs.range.validate((valid, error) => {
            if (valid) {
              resolve();
            } else {
              reject({
                error: error,
                name: "second",
              });
              return;
            }
          });
        });
        const p3 = new Promise((resolve, reject) => {
          let hasErrors = false; // 用于跟踪是否有错误
          this.rule_shoping = []; // 在循环外部初始化数组

          this.configuration.rule_range.forEach((item) => {
            if (item.section_endBool || item.section_startBool) {
              this.$messages.error("请配置区间金额");
              this.activeName = "third";
              hasErrors = true; // 设置标志表示有错误
            }
            if (item.goods_ids.length === 0) {
              this.$messages.error("请配置加购商品");
              this.activeName = "third";
              hasErrors = true; // 设置标志表示有错误
            } else {
              this.rule_shoping.push({
                section_start:Number(item.section_start),
                section_end: Number(item.section_end),
                goods_ids: item.goods_ids,
              });
            }
          });
          if (hasErrors) {
            reject();
          } else {
            resolve(this.rule_shoping); 
          }
        });
       
        const p4 = new Promise((resolve, reject) => {
          if (this.basic.explain != "") {
            resolve();
          } else {
              this.$messages.error("请填写活动说明");
              this.activeName='fourth'
            reject();
          }
          if (this.basic.remark != "") {
            resolve();
          } else {
              this.$messages.error("请填写活动简介");
              this.activeName='fourth'
            reject();
          }
        });
        const p5 = new Promise((resolve, reject) => {
          this.distzengzhi_shuju = {
              is_open:1,
              goods_list:[],
            }
            if( this.plugin_gain.goods_list.length==0){
              this.$messages.error("请为商品配置增值插件");
              this.activeName = "Plugins";
              reject();
            }else{
              this.plugin_gain.goods_list.forEach((item) => {
              this.distzengzhi_shuju.goods_list.push({
                goods_id:item.id,
                award_type:item.award_type,
                node_type:item.node_type,
                node_day:item.node_day,
                integral_num:item.integral_num,
              })
            })
            resolve();
            }
        });

        Promise.all([p1, p2, p3, p4, p5])
          .then(() => {
            let ranges = JSON.parse(JSON.stringify(this.range));
            ranges.user_black = this.joinblackIds.toString();
            if (ranges.appoint_area_select.length <= 0) {
              ranges.appoint_area_select = ''
            }
            ranges.appoint_group_select = ranges.appoint_group_select.toString();
            ranges.appoint_tag_select = ranges.appoint_tag_select.toString();
            ranges.appoint_level_select = ranges.appoint_level_select.toString();
            ranges.appoint_area_select_json = JSON.stringify(ranges.appoint_area_select_json);

            this.distribution_shuju = {
              is_open:this.plugin_retail.is_open,
              goods_list:[],
            }
            if(this.plugin_retail.is_open==0){
              this.distribution_shuju.goods_list = []
            }else{
              this.plugin_retail.goods_list.forEach((item) => {
                  this.distribution_shuju.goods_list.push({
                  goods_id:item.id,
                  award_type:item.award_type,
                  node_type:item.node_type,
                  node_day:item.node_day,
                  level:item.level,
                  goods_rule:item.goods_rule,
                })
            })
          }
            let formdata = {
              goods_ids:this.reward_task_goods_ids,
              plugin_retail:this.distribution_shuju,
              plugin_gain:this.distzengzhi_shuju,
              rule_range:this.rule_shoping,
              ...this.basic,
              ...ranges,
            }
            console.log(formdata)
            if(this.editId) {
              formdata.id = this.editId
            }
            this.loading = true
            SaveSign(formdata).then((res) => {
              if (res.code !== 200 || res.status !== 1) {
                this.$messages.error(res.msg);
                this.loading = false
                return;
              }
              this.loading = false
              this.closedinvitation()
            });
          })
      }
    }
  }
</script>
<style lang="scss">
  .drawer-layout {

    /*1.显示滚动条：当内容超出容器的时候，可以拖动：*/
    .el-drawer__body {
      overflow: auto;
    }

    /*2.隐藏滚动条，太丑了*/
    .el-drawer__container ::-webkit-scrollbar {
      display: none;
    }

    .el-drawer__header {
      background-color: #409eff;
      color: #ffffff;
      padding: 10px 20px;
      margin-bottom: 10px;
    }

    .el-tabs--card {
      height: calc(100vh - 110px);
      /* overflow-y: auto; */
    }

    .el-tab-pane {
      height: calc(100vh - 110px);
      overflow-y: auto;
    }

    .el-tabs__header {
      padding-left: 50px;
      margin: 0;
    }

    .el-tabs__item {
      padding: 0 40px;
    }

    .el-tabs__nav-wrap::after {
      content: "";
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 2px;
      background-color: #ffffff;
      z-index: 1;
    }

    .el-alert--warning.is-light .el-alert__description {
      color: #c77b04;
      font-size: 14px;
    }

    .form-box-item {
      .el-form-item__label {
        font-size: 14px;
        font-weight: 500;
        // width: 96px;
      }

      .el-input {
        width: 250px;
      }
    }
  }
</style>

<style lang="scss" scoped>
  .blockquote-box {
    border-left: 4px solid #409eff;
    padding-left: 16px;
    margin: 16px 0;
    height: 40px;
    line-height: 40px;
    background: #fafafa;
    font-size: 16px;
  }

  .form-box {
    margin: 0 20px;

    .form-box-item {
      padding-bottom: 10px;
      padding-right: 20px;
      font-size: 12px;
      color: #4c4c4c;

      .form-tip {
        font-size: 12px;
        color: #4c4c4c;

        .tip-key {
          font-weight: bold;
          text-decoration: underline;
        }
      }


      .form_text {
        display: inline-block;
        font-size: 14px;
        font-weight: 500;
        color: #606266;
        margin-left: 8px;
      }

      .form-product {
        display: flex;
        font-size: 12px;
        color: #ee3737;
      }

      .Instructions {
        background: #f6f6f6;
        border-radius: 4px;
        padding: 10px;
      }
    }

    .table-top {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;

      .table-top-left {
        display: flex;

        div {
          margin-right: 20px;
        }
      }

      .table-top-right {
        display: flex;

        div {
          margin-left: 20px;
        }
      }
    }

    .table-num {
      margin-left: 5px;
      background: #f0f0f0;
      width: 35px;
      border-radius: 5px;
    }
    .placard-box {
      .placard-title {
        font-size: 14px;
        color: #4893ff;
        width: 200px;
        text-align: center;
        margin-bottom: 10px;
      }

      .placard-tip {
        margin-top: 10px;
        width: 350px;
        color: #6c6c6c;
        line-height: 20px;
        font-size: 12px;
      }
    }
  }

  .button-box {
    margin-bottom: 20px;
    margin-right: 30px;

    .next-button {
      background-color: #eeeeee;
      color: #4c4c4c;
      height: 30px;
    }
  }
  .tips{
    color: #ff4949;
    font-size: 12px;
    line-height: 1;
    padding-top: 4px;
    position: absolute;
    top: 100%;
    left: 0;
  }
</style>
